﻿var TMMobile = function() {
    TMMobile.superclass.constructor.call(this);

    var Elements = {
        loadingScreen: $(".loading-screen")
    };

    var loadingScreenTimeoutId = null;

    var self = this;

    this.TMMService = null;

    this.LeftMenu = {
        container: $("#userLeftMenu"),
        instance: null
    };

    this.TMMData = {};

    this.Pages = {
        Authentication: {
            container: $("#authenticationPage"),
            instance: null
        },
        CompanyConnection: {
            container: $("#companyConnectionPage"),
            instance: null
        },
        Dashboard: {
            container: $("#dashboardPage"),
            instance: null
        },
        EmployeesList: {
            container: $("#employeesListPage"),
            instance: null
        },
        EmployeeInfo: {
            container: $("#employeeInformationPage"),
            instance: null
        },
        CereriConcedii: {
            container: $("#cereriConcediiPage"),
            instance: null
        },
        Settings: {
            container: $("#settingsPage"),
            instance: null
        },
        MyProfile: {
            container: $("#myProfilePage"),
            instance: null
        },
        ChangePassword: {
            container: $("#changePasswordPage"),
            instance: null
        },
        SelectareTipConcediu: {
            container: $("#selectareTipConcediuPage"),
            instance: null
        },
        SelectareSubtipConcediu: {
            container: $("#selectareSubtipConcediuPage"),
            instance: null
        },
        SelectareStatusConcediu: {
            container: $("#selectareStatusConcediuPage"),
            instance: null
        },
        SelectarePunctDeLucru: {
            container: $("#selectarePunctDeLucruPage"),
            instance: null
        },
        SelectareDepartament: {
            container: $("#selectareDepartamentPage"),
            instance: null
        },
        Cerere: {
            container: $("#cererePage"),
            instance: null
        },
        Notifications: {
            container: $("#notificationsPage"),
            instance: null
        },
        IstoricCerere: {
            container: $("#istoricCererePage"),
            instance: null
        },
        CentreCost: {
            container: $("#centreCostPage"),
            instance: null
        },
        SelectareDimensiuniStructuriPage: {
            container: $("#selectareDimensiuniStructuriPage"),
            instance: null
        },
        SelectareDimensiuniPage: {
            container: $("#selectareDimensiuniPage"),
            instance: null
        },
        SelectareFunctie: {
            container: $("#selectareFunctiePage"),
            instance: null
        }
    };

    this.User = {
        Rights: {
            ALL: false,

            AccesModulPontaj: false,
            OperarePontajRealizat: false,
            OperarePontajPlanificat: false,

            AccesModulCereriConcedii: false,
            AdaugareCereriConcedii: false,
            ModificareCereriConcedii: false,
            StergereCereriConcedii: false,
            AprobareCereriConcedii: false,
            RefuzareCereriConcedii: false,
            ReinitializareCereriConcedii: false
        },
        Settings: {
            AutoLogin: true,
            AutoNotifications: true,
            Language: Constants.defaultLanguage,
            ImagesUrl: ''
        },
        IsAlsoEmployee: false,
        PRS_ID: 0,
        PRA_ID: 0,
        POP_ID: 0,
        HasPicture: false,
        DeviceId: "",
        Username: "",
        Company: "",
        CompanyPicUrl: null,
        NumeAngajat: "",
        Roles: new Array(),
        IsOnlyEmployee: false,
        Companies: new Array(),
        getRoleByRoleType: function(roleType) {
            if (!self.User.Roles)
                return null;
            for (var i = 0; i < self.User.Roles.length; i++) {
                var r = self.User.Roles[i];
                if (r.RoleType == roleType)
                    return r;
            }
        },
        IsConnected: false
    };

    this.getAuthenticationData = function() {
        var authData = app.Phone.getAuthData();
        if (!authData)
            authData = $.jStorage.get("auth");
        return authData && authData.POP_ID ? authData : null;
    };

    this.setAuthenticationData = function(authData) {
        if (authData) {
            authData.Companies = self.User.Companies;
            self.setUserData(authData);
        }

        var data = null;
        if (authData) {
            authData.Password = authData.Password;
            data = JSON.stringify(authData);
        }
        app.Phone.setAuthData(data);

        return $.jStorage.set("auth", authData);
    };

    this.setUserData = function(data) {
        self.setRights(data);
        for (var i = 0; i < data.Roles.length; i++) {
            var r = data.Roles[i];
            if (r.RoleType == Roles.S) {
                self.User.IsAlsoEmployee = true;
                self.User.PRS_ID = data.PRS_ID;
                self.User.PRA_ID = data.PRA_ID;
            }
            self.User.Roles.push(r);
        }

        self.User.IsOnlyEmployee = self.User.IsAlsoEmployee && self.User.Roles.length == 1;

        self.User.POP_ID = data.POP_ID;
        self.User.Username = data.Username;
        self.User.Company = data.Company;
        if (data.PRS_ID) {
            self.User.PRS_ID = data.PRS_ID;
            self.User.NumeAngajat = data.NumeAngajat;
        }

        self.User.IsConnected = true;
    };

    this.disconnect = override(self.disconnect, function() {
        self.User.IsConnected = false;
        self.Phone.setNotifications(0);
        if (self.User.DeviceId)
            self.TMMService.PushMessaging.InvalidateDeviceInfo(self.User.DeviceId, Constants.ApplicationId);
        $.jStorage.deleteKey("auth");
        app.Phone.deleteAuthData();
        app.Phone.disconnect();

        if (!app.Phone.getMobilePlatformIndex())
            document.location.reload();
    });

    this.getCurrentSettings = function() {
        var settings = app.Phone.getUserSettings();
        return settings || $.jStorage.get("currentSettings") || self.User.Settings;
    };
    this.setCurrentSettings = function(settings, callback) {
        var data = JSON.stringify(settings);
        app.Phone.setUserSettings(data);
        $.jStorage.set("currentSettings", settings || self.User.Settings);
        self.User.Settings = settings;

        self.User.Settings.ImagesUrl = $("#ImagesUrl");

        if (settings.Language != self.getCurrentLanguage()) {
            self.setCurrentLanguage(settings.Language);
            callback();
        } else callback();
    };

    this.getCurrentLanguage = function() {
        return $.jStorage.get("currentLanguage") || Constants.defaultLanguage;
    };

    this.setCurrentLanguage = function(lang) {
        self.User.Settings.Language = $("#CurrentCulture").val() || Constants.defaultLanguage;
        Globalize.culture(self.User.Settings.Language);
        $.jStorage.set("currentLanguage", self.User.Settings.Language);
    };

    this.setRights = function(authData) {
        if (authData && authData.Roles)
            for (var i = 0; i < authData.Roles.length; i++) {
                var r = authData.Roles[i];
                if (r.Rights)
                    for (var j = 0; j < r.Rights.length; j++) {
                        var right = r.Rights[j];
                        for (var rc in Constants.Authentication.Rights)
                            if (right == Constants.Authentication.Rights[rc])
                                self.User.Rights[rc] = true;
                    }
            }
    };

    this.getCompanyDictionary = function(callback) {
        callback();
        return;

        //TODO - de verificat
        //self.TMMService.TMM.GetDictionary(function (response) {
        //    if (response && response.FinalResult)
        //        for (var i = 0; i < response.FinalResult.length; i++) {
        //            var w = response.FinalResult[i];
        //            self.Resources[w.Key] = w.Value;
        //        }
        //    callback();
        //});
    };

    this.setPageTitle = function() {
        if (self.CurrentPage && self.CurrentPage.instance) {
            self.Phone.setPageTitle(self.CurrentPage.instance.Title);
        }
    };

    this.showLeftMenu = function() {
        if (!self.User.POP_ID)
            return;

        if (!self.LeftMenu.instance) {
            self.LeftMenu.instance = new LeftMenu($("#userLeftMenu"));
            self.Menu = self.LeftMenu;
        }
        if (!self.LeftMenu.instance.isVisible())
            self.LeftMenu.instance.show();
        else self.LeftMenu.instance.hide();
    };

    this.showLoadingScreen = override(self.showLoadingScreen, function() {
        if (!loadingScreenTimeoutId)
            loadingScreenTimeoutId = setTimeout(function() {
                Elements.loadingScreen.fadeIn(300);
            }, Constants.LoadingScreenTimeout);
    });

    this.hideLoadingScreen = override(self.hideLoadingScreen, function() {
        clearTimeout(loadingScreenTimeoutId);
        loadingScreenTimeoutId = null;
        Elements.loadingScreen.stop();
        Elements.loadingScreen.hide();
    });

    this.updateUnreadNotifications = function() {
        if (!self.User.IsConnected)
            return;

        if (self.CurrentPage && self.CurrentPage.instance && self.CurrentPage.instance == app.Pages.Notifications.instance) {
            app.Pages.Notifications.instance.refresh();
            return;
        }

        app.TMMService.TMM.GetUnreadNotificationsCount(function(response) {
            if (!response.Exception) {
                Event.sendEvent(null, 'updateUnreadNotifications', { Nr: response.FinalResult });
                self.Phone.setNotifications(response.FinalResult);
            }
        });
    };

    this.initialize = override(self.initialize, function() {
        $(document).keydown(function(e) {
            if (!app.Phone.getMobilePlatformIndex()) {
                if (e.keyCode == Keys.B)
                    self.goBack();
            }
        });

        var deviceIdFromQueryString = Utils.getQueryString("deviceId");
        if (deviceIdFromQueryString)
            setDeviceId(deviceIdFromQueryString);

        Elements.loadingScreen.bind('click touchstart touchmove', function(e) {
            return Event.stopEvent(e);
        });
    });

    this.goBack = function() {
        if (app.LeftMenu.instance && app.LeftMenu.instance.isVisible())
            app.LeftMenu.instance.hide();
        else if (self.CurrentPage && self.CurrentPage.instance && self.CurrentPage.instance.goBack) {
            app.hideLoadingScreen();
            self.CurrentPage.instance.goBack();
        }
    };

    this.registerDeviceId = function() {
        if (self.User && self.User.DeviceId && self.User.Company) {
            var mobilePlatform = app.Phone.getMobilePlatformIndex();
            self.TMMService.PushMessaging.RegisterDevice(self.User.DeviceId, mobilePlatform, Constants.ApplicationId, self.User.Company, self.User.Username, self.User.PRS_ID, self.getCurrentSettings().Language);
        }
    };
};
extend(TMMobile, MobileApplication);